<script setup>
import {pageofficeOpenFile} from "@/plugins/pageoffice/pageoffice-common.js";
import {restoreToHistory} from "@/api/contract/history.js";
import useAppStore from "@/store/modules/app.js";

const device = computed(() => useAppStore().device);
const {proxy} = getCurrentInstance()
const listLoading = ref(false)
const loading = ref(false)
const historyList = ref(null)
const emits = defineEmits(['getHistoryList'])
const props = defineProps({
  historyButtons: {
    type: Object
  },
  historyOpInfo: {
    type: Object
  },
  isRefreshHistory: {
    type: Boolean
  }
})

watchEffect(() => {
  if (props.isRefreshHistory) {
    getHistoryList()
  }
})

function getHistoryList() {
  listLoading.value = true
  props.historyOpInfo.getListApi(props.historyOpInfo.listQueryParams).then((res) => {
    historyList.value = res
    listLoading.value = false
  })
}

function openFile(row) {
  const historyId = row.id
  props.historyOpInfo.getFileApi(historyId).then(response => {
    const fileInfo = JSON.stringify(response)
    pageofficeOpenFile(props.historyOpInfo.openUrl + historyId, fileInfo)
  })
}

function restoreFile(row) {
  const historyId = row.id
  proxy.$modal.confirmAndExecuteJS('确认要合同还原到当前版本？', confirmRestore, historyId, getHistoryList)
}

function confirmRestore(historyId) {
  restoreToHistory(historyId).then(() => {
    proxy.$modal.msgSuccess('还原成功')
  })
}

function backList() {
  const obj = {path: props.historyOpInfo.backListUrl, query: {t: Date.now()}}
  proxy.$tab.closeOpenPage(obj)
}

</script>

<template>
  <el-row>
    <el-form-item>
      <el-button @click="backList">返 回</el-button>
    </el-form-item>
  </el-row>
  <!-- 表格数据 -->
  <el-table v-loading="loading" :data="historyList">
    <el-table-column label="版本" prop="edition" :show-overflow-tooltip="true" min-width="150"/>
    <el-table-column label="生成时间" align="left" prop="createTime" width="200"/>
    <el-table-column label="操作" :fixed="device === 'desktop' ? 'right' : null" width="250" class-name="small-padding fixed-width">
      <template #default="scope">
        <el-button link type="primary" icon="Edit" @click="openFile(scope.row)">打开</el-button>
        <el-button link type="warning" icon="Edit" @click="restoreFile(scope.row)" v-if="scope.row.restoreButton">还原到当前版本</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>